package spotGUI.sideBar.utils;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import utils.StackTracePrinter;



public class XMLWeatherDataReader {

	private static XMLWeatherDataReader sharedInstance = new XMLWeatherDataReader();
	
	private WeatherData[] weatherData; //Current weather, today's forecast, tomorrow's forecast
	
	private SAXParserFactory factory;
	private InputStream xmlInput;
	private DefaultHandler handler;
	private SAXParser saxParser;
	
	private XMLWeatherDataReader () {

		factory = SAXParserFactory.newInstance();
		try {
			saxParser = factory.newSAXParser();
		} catch (Exception e) {
			StackTracePrinter.print(e);
		}
		handler = new SaxHandler();
	}
	
	private void parseXML (String XML_URL) throws SAXException, IOException {
			xmlInput = new URL(XML_URL).openStream();
			saxParser.parse(xmlInput, handler);
			xmlInput.close();
	}
	
	public void setWeatherData (WeatherData[] weatherData) {
		this.weatherData = weatherData;
	}
	public WeatherData[] getWeatherData (String XML_URL) throws SAXException, IOException {
		parseXML(XML_URL);
		return weatherData;
	}
	
	public static XMLWeatherDataReader getSharedInstance () {
		return sharedInstance;
	}
	
}